//
//  AppDelegate.swift
//  GomroStore
//
//  Created by mac on 2020/11/20.
//

import UIKit
import SnapKit
import Alamofire
import IQKeyboardManagerSwift

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    //MARK: - proterty
    public static var netWorkType:String?
    
    /** 单例对象 */
    private static let _app:AppDelegate = AppDelegate.init()
    public static func app() -> AppDelegate {
        return _app
    }
    

    //MARK: - application
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //网络监测
        DispatchQueue.global().async {
            self.netWorkCheck()
        }
        
        //第三方库初始化
        DispatchQueue.main.async {
           self.initThird()
        }
        
        //启动图动画
        self.startAnimation()
        
        // [S] 开启数据库
        DispatchQueue.global().async {
            FMDBUtils.shareInstance.initDBAndTables()
        }
        // [E] 开启数据库
        
        //输出异常日志
        NSSetUncaughtExceptionHandler { exception in
            print("++++++++++++++++++ RASH ++++++++++++++++++ \n\(exception)")
            print("++++++++++++++++++ Stack Trace ++++++++++++++++++ \n\(exception.callStackSymbols)")
        }
        
        return true
    }
    
    /** 禁止iPad设备旋转导致布局错乱 */
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .portrait
    }
    
    deinit {
        AppDelegate.netWorkType = nil
        NetworkReachabilityManager.default?.stopListening()
    }

    
    //MARK: - lazy load
    /** UIWindow */
    lazy var window: UIWindow? = {
        
        unowned var weakSelf = self
        
        // [S] 设置App 主容器
        let _winDown = UIWindow.init(frame: UIScreen.main.bounds)
        _winDown.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
        
        if UserModel.userIsLogined {
            _winDown.rootViewController = weakSelf.navigation()
        }
        else{
            _winDown.rootViewController = LoginViewController.init()
        }
        
        //设置系统主题色
        if #available(iOS 7.0, *) {
            //tint color 为 高亮颜色
            //tint color默认是蓝色，但是通过改变它的颜色你可以立即让app获得自己独特风格
            _winDown.tintColor = K_APP_TINT_COLOR
        }
        // [S] 设置App 主容器
        
        _winDown.makeKeyAndVisible()
        _winDown.makeKey()
    
        return _winDown
    }()
}


//MARK: - Class custom method
extension AppDelegate {
    
    private func navigation() -> UINavigationController {
        autoreleasepool {
            let _navigation = UINavigationController.init(rootViewController: BaseTabBarController.init())
            
            _navigation.navigationBar.isHidden = true
            _navigation.toolbar.isHidden = true
            
            return _navigation
        }
    }
    
    private func initThird(){
        //IQKeyboardManager 启用
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        
        // 控制键盘上的工具条文字颜色是否用户自定义
        IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor = true
        // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
        IQKeyboardManager.shared.toolbarManageBehaviour = .bySubviews
        // 控制是否显示键盘上的工具条
        IQKeyboardManager.shared.enableAutoToolbar = true
        // 是否显示占位文字
        IQKeyboardManager.shared.shouldShowToolbarPlaceholder = true
        // 设置占位文字的字体
        IQKeyboardManager.shared.placeholderFont = UIFont.boldSystemFont(ofSize: 17)
        // 输入框距离键盘的距离
        IQKeyboardManager.shared.keyboardDistanceFromTextField = 10.0
         
        IQKeyboardManager.shared.registerTextFieldViewClass(YYTextView.classForCoder() as! UIView.Type,
                                                            didBeginEditingNotificationName: NSNotification.Name.YYTextViewTextDidBeginEditing.rawValue,
                                                            didEndEditingNotificationName: NSNotification.Name.YYTextViewTextDidEndEditing.rawValue)
        
        
        //SVProgressHUD
        SVProgressHUD.dismissLoading(isInit: true)
    }
    
    /**
     * 是否有网
     * @return true 有网 false 没网
     */
    func isNetWork() -> Bool {
        return NetworkReachabilityManager.default?.isReachable ?? false
    }
    
    //网络监测
    private func netWorkCheck(){
        NetworkReachabilityManager.default?.startListening(onUpdatePerforming: { status in
            switch(status){
            case .notReachable:
                AppDelegate.netWorkType = "没有网络"
                print("没有网络")
                SVProgressHUD.showInfo(withStatus: "世上最遥远的距离,就是没有网(〒︿〒)")

                DispatchQueue.main.async {
                    //发送本地通知，方便后面使用
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: K_APP_IS_NET_WORK),
                                                    object: nil,
                                                    userInfo: [K_APP_IS_NET_WORK_CODE:404,"type":"网络有些问题，请检查"])
                }

            case .reachable(.cellular):
                print("蜂窝网络")
                AppDelegate.netWorkType = "蜂窝网络"
            case .reachable(.ethernetOrWiFi):
                print("Wifi或以太网")
                AppDelegate.netWorkType = "Wifi或以太网"
            default:
                print("未知网络")
                AppDelegate.netWorkType = "未知网络"
                break
            }

            if status != .notReachable {
                //发送本地通知，方便后面使用
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: K_APP_IS_NET_WORK),
                                                object: nil,
                                                userInfo: [K_APP_IS_NET_WORK_CODE:200,"type":(AppDelegate.netWorkType ?? "未知网络") as Any])
            }
        })
    }
    
    /** 启动图动画 */
    func startAnimation(){
        
        weak var weakSelf = self
        let infoDictionary:[String:Any] = Bundle.main.infoDictionary!
        let strStoryboardName:String = String.init(format:"%@",infoDictionary["UILaunchStoryboardName"] as! CVarArg)
        
        let storyboard:UIStoryboard = UIStoryboard.init(name: strStoryboardName, bundle: nil)
        let viewController:UIViewController = storyboard.instantiateViewController(withIdentifier: "LaunchScreen")
        
        var launchView:UIView? = viewController.view
        if launchView != nil {
            autoreleasepool {
                weakSelf?.window?.addSubview(launchView!)
                
                //执行动画
                UIView.animate(withDuration: 1, animations: {
                    launchView?.alpha = 0.85
                    
                    //图片变大为原来的1.3倍
                    launchView?.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
                }) { (result:Bool) in
                    
                    //动画结束，移除imageView，呈现主界面
                    launchView?.removeFromSuperview()
                    
                    if result {
                        launchView = nil
                    }
                }
            }
        }
    }
    
    func enterMainApp(){
        unowned let weakSelf = self
        let _window:UIWindow = (UIApplication.shared.keyWindow ?? UIApplication.shared.windows.first)!
        _window.rootViewController?.modalTransitionStyle = .flipHorizontal
        
        UIView.transition(with: _window,
                           duration: 0.9,
                           options: UIView.AnimationOptions.transitionFlipFromLeft,
                           animations: {
                            
                            let oldState:Bool = UIView.areAnimationsEnabled
                            UIView.setAnimationsEnabled(false)
                             
                            _window.rootViewController?.dismiss(animated: false, completion: {
                                   print("rootViewController 已移除")
                            })
                            
                            _window.rootViewController?.removeFromParent()
                            _window.rootViewController = nil
                            _window.rootViewController = weakSelf.navigation()
                            
                            UIView.setAnimationsEnabled(oldState)
                            
        }, completion: { (result:Bool) in
            //关闭键盘
            _window.endEditing(true)
            
            print("进入主程序")
        })
    }
    
}
